package 文件操作;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

/**
 * properties文件操作
 *
 * @author xgp
 */
public class PropertiesUtil {
    private Properties properties;
    private final String path;

    public PropertiesUtil(String path) throws IOException {
        this.path = path;
        properties = new Properties();
        properties.load(new FileReader(path));
    }

    /**
     * 创建properties文件
     *
     * @throws IOException
     */
    public void create() throws IOException {
        properties.store(new FileWriter(path), null);
    }

    /**
     * 读取properties文件
     *
     * @throws IOException
     */
    public Properties read() throws IOException {
        return this.properties;
    }

    /**
     * 设置key-value
     *
     * @param key   键
     * @param value 值
     */
    public void set(String key, String value) {
        this.properties.setProperty(key, value);
    }

    /**
     * 保存properties文件<br>
     * 在调用set之后必须保存
     *
     * @throws IOException
     */
    public void save() throws IOException {
        properties.store(new FileWriter(path), null);
    }

    /*测试*/
    public static void main(String[] args) throws IOException {
        PropertiesUtil propertiesUtil = new PropertiesUtil("user.properties");
        propertiesUtil.create();
        propertiesUtil.set("name", "吴小刚");
        propertiesUtil.set("age", "21");
        propertiesUtil.set("sex", "男");
        Properties p = propertiesUtil.read();
        for (Object key : p.keySet()) {
            System.out.println(key + "=" + p.getProperty((String) key));
        }
        propertiesUtil.save();

        propertiesUtil.set("age", "18");
        propertiesUtil.save();

        p = propertiesUtil.read();
        for (Object key : p.keySet()) {
            System.out.println(key + "=" + p.getProperty((String) key));
        }

    }
}
